<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="课程名称" prop="courseName">
        <el-select v-model="queryParams.courseName" placeholder="请选择课程名称" clearable>
          <el-option
            v-for="dict in courseDictList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.label"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-if="queryParams.courseName!=null" label="学生姓名" prop="teacherId">
        <el-input
          v-model="queryParams.studentName"
          placeholder="请输入学生姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item v-if="queryParams.courseName!=null">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="courseList">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" label="序号" align="center" width="60"/>
      <el-table-column label="学生姓名" align="center" prop="name" />
      <el-table-column label="性别" align="center" prop="sex" />
      <el-table-column label="年龄" align="center" prop="age" />
      <el-table-column label="课程名称" align="center" prop="courseName" />
      <el-table-column label="分数" align="center" prop="score" />
      <el-table-column label="评价" align="center" prop="rateScore" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
         <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="updateStudentScore(scope.row)"
          >修改成绩</el-button>
          <el-button
            v-if="scope.row.rateScore == null"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="evaForStudent(scope.row)"
          >为学生评价</el-button>
          <el-button
            v-else
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="evaForStudentUpdate(scope.row)"
          >修改学生评价</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="handleQuery"
    />


    <el-dialog
      @close="closeScore"
      :title="'为学生：'+(courseItem==null?'‘无’':courseItem.name)+'评价'"
      :visible.sync="choseVisible"
      width="30%"
      center>
        <el-form :model="ruleForm" ref="ruleForm" :rules="rules2" label-width="80px">
          <el-form-item label="成绩" prop="studentScore">
            <el-input-number v-model="ruleForm.studentScore" :min="1" :max="10" label="请输入评分"></el-input-number>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="choseVisible = false">取 消</el-button>
          <el-button type="primary" @click="evaluate">确 定</el-button>
        </div>
    </el-dialog>

<!--    教师为学分打成绩-->
    <el-dialog
      @close="closeScore2"
      :title="'为学生：'+(courseItem==null?'‘无’':courseItem.name)+' ['+(courseItem==null?'‘无’':courseItem.courseName)+'] 课程打分'"
      :visible.sync="scoreVisible"
      width="30%"
      center>
        <el-form :model="scoreForm" ref="scoreForm" :rules="rules" label-width="80px">
          <el-form-item label="评分" prop="studentScore">
            <el-input-number v-model="scoreForm.studentScore" :min="1" :max="100" label="请输入评分"></el-input-number>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="scoreVisible = false">取 消</el-button>
          <el-button type="primary" @click="grading">确 定</el-button>
        </div>
    </el-dialog>
  </div>
</template>

<script>

import {getInfo} from "@/api/login";
import {
  getCourse,
  getStudent,
  rateStudent,
  getStudentRate,
  rateStudentScore,
  gradingScore
} from "@/api/courseSystem/teach";

export default {
  name: "manageStudent",
  data() {
    return {
      scoreVisible:false,
      ruleForm:{
        studentScore:null
      },
      scoreForm:{
        studentScore:null
      },
      courseItem:null,
      choseVisible:false,
      courseDictList:[],
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 课程表格数据
      courseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        des: null,
        courseName: null,
        courseId: null,
        teacherId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules2: {
        studentScore: [
          { required: true, message: '请输入您的评分', trigger: 'blur' },
        ],
      },
      rules: {
        studentScore: [
          { required: true, message: '请输入成绩', trigger: 'blur' },
        ],
      }
    };
  },
  created() {
    this.getList();
    this.$message.success('请先选择课程后，在进行搜索')
  },
  methods: {
    updateStudentScore(row){
      if (row.score!=null){
        this.scoreForm.studentScore = row.score;
      }
      this.courseItem = JSON.parse(JSON.stringify(row))
      this.scoreVisible=true;
    },
    grading(){
      this.$refs['scoreForm'].validate((valid) => {
        if (valid) {
          getInfo().then(res=>{
            let courseId = '';
            this.courseDictList.forEach(item=>{
              if (item.label==this.queryParams.courseName){
                courseId = item.value
              }
            })
            gradingScore({studentId:this.courseItem.studentId,
              courseId:courseId,
              score:this.scoreForm.studentScore}).then(response=>{
              if (response.code==200){
                this.$message.success('评分成功')
                this.scoreVisible = false;
                this.handleQuery();
              }else {
                this.scoreVisible = false;
                this.$message.error('评分失败啦')
              }
            })
          })
        }
      })
    },
    evaluate(){
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          if (this.courseItem.rateScore!=null){
            this.courseItem.score = this.ruleForm.studentScore
            getInfo().then(res=>{
              this.courseItem.teachId = res.user.userName;
              rateStudentScore(this.courseItem).then(res=>{
                if (res.code==200){
                  this.$message.success('修改成功')
                  this.choseVisible = false;
                  this.handleQuery();
                }
              })
            })
          }else {
            if (this.ruleForm.studentScore!=null) {
              if (this.courseItem!=null){
                getInfo().then(response=>{
                  // {techId,studentId,score}
                  rateStudent({teachId:response.user.userId,studentId:this.courseItem.studentId,score:this.ruleForm.studentScore}).then(res=>{
                    if (res.code==200){
                      this.$message.success('评价成功')
                      this.choseVisible = false
                      this.handleQuery();
                    }else {
                      this.$message.error('评价失败啦')
                    }
                  })
                })
              }else {
                this.$message.warning('未选择学生')
              }
            }
          }
        }
      })
    },
    closeScore(){
      this.courseItem = null;
      this.ruleForm.studentScore = null;
    },
    closeScore2(){
      this.courseItem = null;
      this.scoreForm.studentScore = null;
    },
    evaForStudent(row){
      this.courseItem = JSON.parse(JSON.stringify(row));
      this.ruleForm.studentScore = '';
      this.choseVisible = true;
    },
    // 回显评价
    evaForStudentUpdate(row){
      console.log(row)
      this.courseItem = JSON.parse(JSON.stringify(row))
      this.ruleForm.studentScore = null;
      getInfo().then(res=>{
        getStudentRate(row.studentId,res.user.userName).then(res=>{
          console.log('===')
          if (res.code==200){
            this.ruleForm.studentScore = res.data.score;
            this.choseVisible = true;
          }else {
            this.$message.warning('查询学生：'+row.name+'的评价出错啦')
          }
        })
      })
    },
    //初始下列列表框
    getList() {
      // this.loading = true;
      getInfo().then(res=>{
        getCourse(res.user.userName).then(response=>{
          if (response.code==200){
            if(response.data.rows==null||response.data.rows.length <= 0) return;
            let list = [];
            response.data.rows.forEach(item=>{
              list.push({value:item.courseId,label:item.courseName});
            })
            this.courseDictList = list;
            console.log(list)
          }else {
            this.$message.error('查询下拉列表出错啦')
          }
        })
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        courseId: null,
        des: null,
        courseName: null,
        teacherId: null,
        teachType: null,
        status: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      if (this.queryParams.courseName!=null){
        if (this.courseDictList.length<0) return;
        let courseId = '';
        this.courseDictList.forEach(item=>{
          if (item.label==this.queryParams.courseName){
            courseId = item.value;
          }
        })
        getInfo().then(res=>{
          this.loading = true;
          getStudent(res.user.userName,courseId,this.queryParams).then(response=>{
            if (response.code!=200){
              this.$message.error("查询出错啦")
            }else {
              if (response.data.rows.length>0){
                response.data.rows.forEach(item=>{
                  item.courseName = this.queryParams.courseName
                })
              }
              this.courseList = response.data.rows;
              this.total = response.data.total;
              this.$message.success('查询成功');
            }
            this.loading  = false;
          })
        })
      }else {
        this.$message.warning('请输入课程名');
      }
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.courseList = [];
      this.queryParams.courseName = null;
      this.queryParams.studentName = null;
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加课程";
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          /*if (this.form.courseId != null) {
            updateCourse(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCourse(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }*/
        }
      });
    },

  }
};
</script>
